<template>
	<div class="add-car">
		<nav-header>
			<template slot="menuBefore">
				<li><router-link to="/affairs/vehicle/vehicle-list" tag="a">车辆管理</router-link></li>
				<li class="gap">&gt;</li>
			</template>
            <li v-if="idEdit">编辑车辆</li>
		</nav-header>

        <el-form 
            :model="addForm" 
            :rules="rules" 
            ref="addForm" 
            label-width="200px" 
            class="add-form" 
            label-position="left"
            v-loading="loading.status" 
            :element-loading-text="loading.txt">
            <el-form-item label="厂牌型号：" prop="brand">
                <el-input v-model="addForm.brand" maxlength="20" placeholder="20个字符内"></el-input>
            </el-form-item>
            <el-form-item label="车牌号：" prop="license">
                <el-input v-model="addForm.license" maxlength="20" placeholder="20个字符内"></el-input>
            </el-form-item>
            <el-form-item label="排量：">
                <el-input v-model="addForm.displacement" maxlength="10" placeholder="10个字符内"></el-input>
            </el-form-item>
            <el-form-item label="车身颜色：" prop="carColor">
                <el-input v-model="addForm.carColor" placeholder="10个字符内" maxlength="10"></el-input>
            </el-form-item>
            <el-form-item label="座位数：" prop="seat">
                <el-input-number 
                    class="input-number-text"
                    v-model="addForm.seat" 
                    controls-position="right" 
                    :min="1" 
                    :max="99"
                    :precision="0">
                </el-input-number>
            </el-form-item>
            <el-form-item label="变速箱：">
                <el-select v-model="addForm.gears">
                    <el-option label="手动" :value="1"></el-option>
                    <el-option label="自动" :value="2"></el-option>
                    <el-option label="手自一体" value="3"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="发动机车架号后6位：" prop="vin">
                <el-input v-model="addForm.vin" maxlength="6" placeholder="请输入6位数"></el-input>
            </el-form-item>
            <el-form-item label="发动机登记证书后7位：" prop="certificate">
                <el-input v-model="addForm.certificate" maxlength="7" placeholder="请输入7位数"></el-input>
            </el-form-item>
            <el-form-item label="发动机：">
                <el-input v-model="addForm.engine" maxlength="30" placeholder="30个字符内"></el-input>
            </el-form-item>
            <el-form-item label="车辆类型：">
                <el-select v-model="addForm.modeId">
                    <el-option v-for="(item, inx) in modeList" :key="inx" :label="item.name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="注册日期：">
                <el-date-picker
                    v-model="addForm.registerDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择行驶证证上的日期"
                    style="width:100%">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="商业保险：" class="addform-insurance" prop="buyDate">
                <el-radio-group v-model="addForm.insurance" @change="changeInsurance">
                    <el-radio :label="0">无商业保险</el-radio>
                    <el-radio :label="1">已买商业保险</el-radio>
                </el-radio-group>
                <span class="insurance-buy-date" v-if="addForm.insurance === 1">
                    <span>购买日期：</span>
                    <el-date-picker
                        v-model="addForm.buyDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择行驶证证上的日期"
                        style="width:100%">
                    </el-date-picker>
                </span>
            </el-form-item>
            <el-form-item label="车辆性质：">
                <el-select v-model="addForm.nature">
                    <el-option label="职务配车" :value="1"></el-option>
                    <el-option label="公务用车" :value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="车辆照片：" class="car-picture">
                <uploader 
                    :options="uploadOptions" 
                    :autoStart="true" 
                    ref="uploader" 
                    :file-status-text="statusText"
                    @files-submitted="fileSubmit"
                    @file-removed="fileRemoved" 
                    @file-success="fileSuccess" 
                    @file-error="fileFail"  
                    class="uploader-example">
                        <uploader-unsupport></uploader-unsupport>
                        <div class="car-picture-show" v-for="(item, inx) in addForm.picture" :key="inx">
                            <div  class="cover-box">
                                <img :src="BASE_URL + item.file_path" />

                                <div class="uploader-close-box">
                                    <label class="el-upload-list__item-status-label" @click.stop="deletImg(inx)">
                                        <transition name="el-fade-in-linear">
                                            <i class="el-icon-upload-success el-icon-check"></i>
                                        </transition>
                                        <transition name="el-fade-in-linear">
                                            <i class="el-icon-close"></i>
                                        </transition>
                                    </label>
                                </div>
                            </div>
                        </div>
                        <uploader-btn :directory="false" :attrs="attrs" :single="true" v-if="addForm.picture.length < 9">
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                        </uploader-btn>
                </uploader>
            </el-form-item>
            <el-form-item label="备注">
                <el-input
                    type="textarea"
                    placeholder="在此输入备注"
                    :rows="4"
                    v-model="addForm.remark"
                    maxlength="140"
                    show-word-limit>
                </el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="resetForm" plain>取消</el-button>
                <el-button type="primary" @click="submitForm('addForm')">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {uploaderFileFail} from './../../../tools/tool';

export default {
    data() {
        return {
            idEdit: false, // 是否编辑
            selectFileShow: true,//是否显示选择文件按钮
            uploadRetryTimes: 100,//文件最大重传次数
            previewImgURL: null, // 图片预览
            modeList: [], // 车辆类型列表
            imageType: ['image/jpeg', 'image/bmp', 'image/png'], // 上传图片格式
            loading: {
                status: false,
                txt: '保存数据...'
            },
            addForm: {
                brand: '', // 厂牌型号
                license: '', // 车牌号
                displacement: '', // 排量
                carColor: '', // 车身颜色
                seat: undefined, // 座位数
                gears: 1, // 变速箱 
                vin: '', // 车架号
                certificate: '', // 登记证书
                engine: '', // 发动机
                modeId: 1, // 车辆类型
                registerDate: '', // 注册日期
                insurance: 0, // 商业保险
                buyDate: '123', // 购买日期
                nature: 1, // 车辆性质
                picture: [], // 车辆照片
                remark: '', // 备注
            },
            rules: {
                brand: [
                    { required: true, message: '请输入厂牌型号', trigger: 'blur' }
                ],
                license: [
                    { required: true, message: '请输入车牌号', trigger: 'blur' }
                ],
                carColor: [
                    { required: true, message: '请输入车身颜色', trigger: 'blur' }
                ],
                vin: [{min: 6, max: 6, message: '请输入6位数', trigger: 'blur' }],
                certificate: [{min: 7, max: 7, message: '请输入7位数', trigger: 'blur' }],
                buyDate: [{required: true, message: '请输入购买日期', trigger: ['change', 'blur']}]
            },
            attrs: {
                accept: ['image/*']
            },
            statusText: {
                success: '上传成功',  
                error: '上传出错',  
                uploading: '正在上传...',  
                paused: '暂停',  
                waiting: '等待上传'  
            },
            uploadOptions: {
                target: this.BASE_URL + '/api/resource/res_upload',
                testChunks: false,
                headers: {Authorization: `Bearer ` + this.$g.access_token},
            },
        }
    },
    created() {
        this.idEdit = this.$route.params.id ? true : false;
        this.getModeList();

        if (this.idEdit) {
            this.getInfo();
        }
    },
    methods: {
        /**
         * 切换商业保险选项
         */
        changeInsurance(val) {
            if (val === 0) {
                this.addForm.buyDate = '123';
            } else {
                this.addForm.buyDate = undefined;
            }

            this.$nextTick(() => {
                this.$refs.addForm.clearValidate('buyDate');
            })
        },
        /**
         * 获取编辑信息
         */
        getInfo() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;

                if (!is_empty(res.data)) {
                    let picture = [];
                    res.data.image.forEach(item => {
                        picture.push({
                            file_name: '',
                            file_path: item,
                            post_fix: ''
                        })
                    })

                    this.addForm = {
                        brand: res.data.brand,
                        license: res.data.number,
                        displacement: res.data.output,
                        carColor: res.data.color,
                        seat: res.data.seat,
                        gears: +res.data.gearbox,
                        vin: res.data.box_num,
                        certificate: res.data.cer_num,
                        engine: res.data.eng_num,
                        modeId: res.data.type_id,
                        registerDate: res.data.reg_day,
                        insurance: +res.data.insure,
                        buyDate: res.data.insure_day ? res.data.insure_day : '123',
                        nature: +res.data.property,
                        picture: picture,
                        remark: res.data.comment,
                    }
                }
            })
            let params = {
                id: this.$route.params.id,
                with_image: 1
            }

            this.$ajax.get('api/car/single', {params, func:{success: success}})
        },
        /**
         * 获取车辆类型列表
         */
        getModeList() {
            const success = (res=>{
                this.modeList = res.data;
            })
            const params = {
                in_use: 0 // 是否已有汽车类型（1：是，0：否（默认））
            }

            this.$ajax.get('api/car/typelists', {func: {success: success}})
        },
        /**
         * 保存添加车辆
         */
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.idEdit) {
                        let yes = (res => {
                            this.saveInfo();
                        })
                        let cancel = (res => {
                            this.$router.push('/affairs/vehicle/vehicle-detail/' + this.$route.params.id);
                        })

                        this.e_confirm({yes: yes, cancel: cancel, txt: '是否要保存车辆信息修改?'});
                    } else {
                        this.saveInfo();
                    }
                } else {
                    return false;
                }
            });
        },
        saveInfo() {
            this.loading.status = true;
            let picture = [];

                this.addForm.picture.forEach(item => {
                    picture.push(item.file_path);
                })
        
            let params = {
                type_id: this.addForm.modeId,
                number: this.addForm.license,
                brand: this.addForm.brand,
                output: this.addForm.displacement,
                color: this.addForm.carColor,
                seat: this.addForm.seat,
                gearbox: this.addForm.gears,
                eng_num: this.addForm.engine,
                cer_num: this.addForm.certificate,
                box_num: this.addForm.vin,
                reg_day: this.addForm.registerDate,
                insure: this.addForm.insurance,
                insure_day: this.addForm.insurance === 0 ? undefined : this.addForm.buyDate,
                property: this.addForm.nature,
                comment: this.addForm.remark,
                path: picture
            }

            const success = (res => {
                this.$message.success(res.msg);
                
                if (this.idEdit) {
                    this.$router.push('/affairs/vehicle/vehicle-detail/' + this.$route.params.id);
                } else {
                    this.$router.push('/affairs/vehicle/vehicle-list');
                }
            })
            const fail = (res => {
                this.$message.error(res.msg);
                this.loading.status = false;
            })

            if (this.idEdit) {
                params.id = this.$route.params.id;
                this.$ajax.put("api/car/single", params, {func: {success: success, fail: fail}});
            } else {
                this.$ajax.post("api/car/single", params, {func: {success: success, fail: fail}});
            }
        },
        /**
         * 取消添加车辆
         */
        resetForm() {
            this.$router.go(-1);
        },
        /**
         * 删除图片
         * @param {Number} inx 要删除图片的下标
         */
        deletImg(inx) {
            this.addForm.picture.splice(inx, 1);
            this.$refs.uploader.uploader.removeFile(this.$refs.uploader.uploader.fileList[inx]);
        },
        /**
         * 过滤文件格式
         */
        fileSubmit(files, fileList, event){
            for (let i=0; i<fileList.length; i++) {
                let file_type = fileList[i].fileType.toLocaleLowerCase();

                if(!this.imageType.includes(file_type)){
                    this.$message.warning('只允许上传 bmp/jpg/jpeg/png 格式图片');
                    this.$refs.uploader.uploader.removeFile(fileList[i]);

                    return false;
                } else if (fileList[i].size > 10240000) {
                    this.$message.warning("只允许上传10M以内的文件");
                    this.$refs.uploader.uploader.removeFile(fileList[i]);
                    return false;
                } else {
                    this.previewImgURL = window.URL.createObjectURL(fileList[i].file);
                    this.selectFileShow = false;
                }
            }
        },
        /**
         * 上传成功回调
         */
        fileSuccess (rootFile, file, message, chunk) { 
            let mess = eval('(' + message + ')');
            mess = handleResponseData( mess );

            if(parseInt(mess.data.status) === 1 ){
                this.previewImgURL = mess.data.file_path;
                this.addForm.picture.push({
                    file_name: mess.data.file_name,
                    file_path: mess.data.file_path,
                    post_fix: mess.data.post_fix
                })
            }
        },
        /**
         * 上传失败回调
         */
        fileFail(rootFile, file, message, chunk) {
            uploaderFileFail(this, this.$refs.uploader.uploader, file, message);
        },
        /**
         * 移除文件
         */
        fileRemoved(file){
            this.selectFileShow = true;
            this.previewImgURL = '';
        },
    }
}
</script>

<style lang="scss">
    .add-car {
        .input-number-text {
            width: 100%;

            >span {
                display: none;
            }

            input {
                text-align: left;
            }
        }

        .insurance-buy-date {
            position: absolute;
            left: 185px;
            bottom: 0px;

            >span {
                display: inline-block;
            }

            >div {
                display: inline-block;
                width: 240px !important;

                input {
                    height: 30px;
                    line-height: 30px;
                }
            }
        }

        .add-form {
            .el-form-item__content {
                width: 500px;
            }

            .addform-insurance {
                position: relative;

                .el-radio-group {
                    label:first-child {
                        display: block;
                        margin-bottom: 18px;
                    }
                }
            }
        }

        .car-picture {
            .el-form-item__content {
                width: 600px;
            }

            .uploader-btn {
                display: inline-block;
                width: 190px;
                height: 190px;
                background: #FFFFFF;
                vertical-align: top;
                border: 1px dashed #ddd;
                box-sizing: border-box;

                i  {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    font-size: 60px;
                    color: #ddd;
                }
            }

            .car-picture-show {
                display: inline-block;
                width: 200px;
            }

            .cover-box {
                position: relative;
                display: flex;
                justify-content: center;
                align-items: center;
                width: 190px;
                height: 190px;
                overflow: hidden;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }

                .uploader-close-box {
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    z-index: 99;
                    overflow: hidden;

                    .el-upload-list__item-status-label {
                        display: block;
                        position: absolute;
                        right: -17px;
                        top: -7px;
                        width: 46px;
                        height: 26px;
                        background: #13ce66;
                        text-align: center;
                        transform: rotate(45deg);
                        box-shadow: 0 1px 1px #ccc;
                        .el-icon-check {
                            position: absolute;
                            left: 17px;
                            font-size: 12px;
                            margin-top: 12px;
                            color: #fff;
                            transform: rotate(-45deg);
                            font-family: 'element-icons' !important;
                            speak: none;
                            font-style: normal;
                            font-weight: normal;
                            font-variant: normal;
                            text-transform: none;
                            line-height: 1;
                            vertical-align: baseline;
                            display: inline-block;
                            -webkit-font-smoothing: antialiased;
                        }
                        .el-icon-check:before {
                            content: "\E6DA";
                        }
                        .el-icon-close {
                            display: none;
                        }
                    }
                }
                .uploader-close-box:hover {
                    background: rgba(0, 0, 0, .3);
                    .el-upload-list__item-status-label {
                        top: -4px;
                        right: -15px;
                        background: #f56c6c;
                        box-shadow: none;
                        cursor: pointer;
                        .el-icon-check {
                            display: none;
                        }
                        .el-icon-close {
                            position: absolute;
                            transform: rotate(-45deg);
                            top: 10px;
                            color: #fff;
                            right: 16px;
                            font-size: 12px;
                            font-family: 'element-icons' !important;
                            speak: none;
                            font-style: normal;
                            font-weight: normal;
                            font-variant: normal;
                            text-transform: none;
                            line-height: 1;
                            vertical-align: baseline;
                            display: inline-block;
                            -webkit-font-smoothing: antialiased;
                        }
                        .el-icon-close:before {
                            content: "\E6DB";
                        }
                    }
                }
            }
        }
    }
</style>
